package com.szdtoo.controller;


import com.szdtoo.annotation.SystemLog;
import com.szdtoo.response.Result;
import com.szdtoo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @SystemLog("系统登录")
    @RequestMapping(value = "doLogin",method = RequestMethod.POST)
    @ResponseBody
    public Result doLogin(String username, String password, Boolean rememberMe) throws ServletException, IOException {
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()) {
            return Result.success("已登录过",null);
        }
        if(rememberMe != null && rememberMe) {
            token.setRememberMe(true);
        }
        subject.login(token);
        return Result.success("登录成功",null);
    }



    @SystemLog("系统退出")
    @RequestMapping(value = "doLogout", method = RequestMethod.GET)
    @ResponseBody
    public Result doLogout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success("退出成功",null);
    }


    @RequestMapping(value = "unauthc", method = RequestMethod.GET)
    @ResponseBody
    public Result unauthc() {
        return Result.redirect("未登录");
    }

}
